package com.lagou.rabbitmq.service;

import com.lagou.rabbitmq.entity.PayInfo;
import com.lagou.rabbitmq.enums.OrderStatusEnum;
import com.lagou.rabbitmq.enums.PayStatusEnum;
import com.lagou.rabbitmq.enums.PayTypeEnum;
import com.lagou.rabbitmq.mapper.PayInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class PayService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayInfoMapper payInfoMapper;

    public Integer pay(Long userId, Long orderId) throws Exception {

        Integer orderStatus = orderService.getOrderStatusById(userId, orderId);
        if (OrderStatusEnum.UNPAID.getCode().equals(orderStatus)) {
            // 插入支付记录
            PayInfo payInfo = new PayInfo();
            payInfo.setUserId(userId);
            payInfo.setOrderId(orderId);
            payInfo.setSerialNumber(UUID.randomUUID().toString());
            payInfo.setPayType(PayTypeEnum.ALIPAY.getCode());
            payInfo.setPayPrice(4800L);
            payInfo.setStatus(PayStatusEnum.SUCCESS.getCode());
            payInfoMapper.add(payInfo);

            // 修改订单状态为已支付
            orderService.paidOrder(userId, orderId);

            return PayStatusEnum.SUCCESS.getCode();

        } else if (OrderStatusEnum.PAID.getCode().equals(orderStatus)) {
            return PayStatusEnum.REPEAT.getCode();

        } else {
            return PayStatusEnum.FAILED.getCode();
        }
    }
}
